package com.android.love;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.json.JSONException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.love.net.NetWorkTask;
import com.android.love.net.UriHelper;
import com.android.love.ui.BetterActivityHelper;
import com.android.love.ui.DetailActivity;
import com.android.love.ui.ViewpagerActivity;
import com.android.love.util.Constant;
import com.android.love.util.DeviceUtil;
import com.android.love.util.LogUtil;
import com.android.love.util.Sputil;
import com.android.love.util.StringsUtil;
import com.android.love.vo.Goods;
import com.android.love.vo.Meixiu;
import com.android.love.vo.MyRequest;
import com.android.love.vo.UserInfo;
import com.igexin.sdk.Consts;

public class GexinSdkMsgReceiver extends BroadcastReceiver implements Constant {
	private static final String TAG = "GexinSdkMsgReceiver";

	protected String ticker; // 状态栏消息

	protected String title; // 标题

	protected String text; // 文本信息

	private Context context;

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		Bundle bundle = intent.getExtras();
		LogUtil.d(TAG, "onReceive() action=" + bundle.getInt("action"));
		switch (bundle.getInt(Consts.CMD_ACTION)) {

		case Consts.GET_MSG_DATA:
			// 获取透传数据
			// String appid = bundle.getString("appid");
			byte[] payload = bundle.getByteArray("payload");

			if (payload != null) {
				String data = new String(payload);
				LogUtil.i(TAG, "Got Payload:" + data);

				JSONObject jsonObject = JSON.parseObject(data);
				String action = jsonObject.getString("action");
				ticker = jsonObject.getString("ticker");
				title = jsonObject.getString("title");
				text = jsonObject.getString("text");
				if ("goods".equals(action)) {
					// {"action": "goods","ticker":
					// "tickertickerticker","title": "titletitle","text":
					// "texttexttext","goods": {"goods_id": 8133, "goods_image":
					// "http://www.aiai69.com/ware/goods/orig/2/8/8133.jpg","goods_name":
					// "盛开的罂粟花-碗","price": 385.75, "old_price": 77,
					// "images_item":
					// ["http://www.aiai69.com/ware/goods/orig/2/8/8133.jpg","http://www.aiai69.com/ware/goods/orig/2/8/8133.jpg","http://www.aiai69.com/ware/goods/orig/2/8/8133.jpg"
					// ],"desc_text": "商品文字描述", "desc_image":
					// "http://www.aiai69.com/ware/goods/orig/2/8/8133.jpg","color":
					// ["红色","紫色","绿色"],"size": [ "S","XL","M" ],"format":
					// ["十二支套装","十三支套装", "二十支套装" ]}}
					String goodStr = jsonObject.getString("goods");
					Goods goods = jsonObject.parseObject(goodStr, Goods.class);
					Intent goodIntent = new Intent(MyApplication.getInstance(),
							DetailActivity.class);
					goodIntent.putExtra("type", 1);
					goodIntent.putExtra("singleGoods", goods);
					sendNotificationMessage(goodIntent);
				}
				if ("album".equals(action)) {
					// {"action": "album","ticker":
					// "tickertickerticker","title": "titletitle","text":
					// "texttexttext","album": { "album_id": "16","image":
					// "http://aiai.qiniudn.com/meixiuimage_16.jpg","photo_count":
					// "0","price": "21.00","purchased": 0,"title":
					// "21","viewer_count": "3"}}
					String albumStr = jsonObject.getString("album");
					Meixiu meixiu = jsonObject.parseObject(albumStr,
							Meixiu.class);
					Intent albumIntent = new Intent(context,
							ViewpagerActivity.class);
					albumIntent.putExtra("meixiu", meixiu);
					albumIntent.putExtra("position", 0);
					sendNotificationMessage(albumIntent);
				}
				LogUtil.d(TAG, "自定义消息处理成功!");
				LogUtil.d(TAG, "ticker:" + ticker);
				LogUtil.d(TAG, "title:" + title);
				LogUtil.d(TAG, "text:" + text);

				// Log.d("GexinSdkDemo", "Got Payload:" + data);
				// if (GexinSdkDemoActivity.tLogView != null)
				// GexinSdkDemoActivity.tLogView.append(data + "\n");

			}
			break;
		case Consts.GET_CLIENTID:
			// 获取ClientID(CID)
			// 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
			String cid = bundle.getString("clientid");
			LogUtil.i(TAG, "GET_CLIENTID----" + cid);
			// BetterActivityHelper.newMessageDialog(context, "获取ClientID",
			// cid+"", android.R.drawable.ic_dialog_info).show();

			Sputil sp = new Sputil(context);
			sp.setValue("cid", cid);
			
			register(cid);
			// if (GexinSdkDemoActivity.tView != null)
			// GexinSdkDemoActivity.tView.setText(cid);
			break;

		case Consts.BIND_CELL_STATUS:
			LogUtil.i(TAG, "BIND_CELL_STATUS----");
			// String cell = bundle.getString("cell");
			//
			// Log.d("GexinSdkDemo", "BIND_CELL_STATUS:" + cell);
			// if (GexinSdkDemoActivity.tLogView != null)
			// GexinSdkDemoActivity.tLogView.append("BIND_CELL_STATUS:" + cell +
			// "\n");
			break;
		case Consts.THIRDPART_FEEDBACK:
			LogUtil.i(TAG, "THIRDPART_FEEDBACK----");
			// sendMessage接口调用回执
			// String appid = bundle.getString("appid");
			// String taskid = bundle.getString("taskid");
			// String actionid = bundle.getString("actionid");
			// String result = bundle.getString("result");
			// long timestamp = bundle.getLong("timestamp");
			//
			// Log.d("GexinSdkDemo", "appid:" + appid);
			// Log.d("GexinSdkDemo", "taskid:" + taskid);
			// Log.d("GexinSdkDemo", "actionid:" + actionid);
			// Log.d("GexinSdkDemo", "result:" + result);
			// Log.d("GexinSdkDemo", "timestamp:" + timestamp);
			break;
		default:
			break;
		}
	}

	/**
	 * 发送通知栏消息
	 */
	private void sendNotificationMessage(Intent intent) {
		NotificationManager manager = (NotificationManager) MyApplication
				.getInstance().getSystemService(
						MyApplication.getInstance().NOTIFICATION_SERVICE);
		Notification notification = new Notification();

		notification.flags = Notification.FLAG_AUTO_CANCEL;// 当点击通知栏消息后，该通知不取消

		// 设置显示在手机最上边的状态栏的图标
		notification.icon = R.drawable.icon;
		// 当前的notification被放到状态栏上的时候，提示内容
		notification.tickerText = ticker;

		/***
		 * l notification.contentIntent:一个PendingIntent对象，当用户点击了状态栏上的图标时，
		 * 该Intent会被触发 notification.contentView:我们可以不在状态栏放图标而是放一个view
		 * notification.deleteIntent 当当前notification被移除时执行的intent
		 * notification.vibrate 当手机震动时，震动周期设置
		 */
		// 添加声音提示
		notification.defaults = Notification.DEFAULT_SOUND;
		// audioStreamType的值必须AudioManager中的值，代表着响铃的模式
		notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;
		//
		// Intent intent = new Intent(MyApplication.getInstance(),
		// DetailActivity.class);
		// intent.putExtra("type", 1);
		// intent.putExtra("goods", (Serializable) goods);
		// intent.putExtra("position", 0);
		// intent.putExtra("topgoods", (Serializable)goods);
		// startActivity(intent);

		PendingIntent pendingIntent = PendingIntent.getActivity(
				MyApplication.getInstance(), 0, intent,
				PendingIntent.FLAG_ONE_SHOT);
		// 点击状态栏的图标出现的提示信息设置
		if (text.length() > 20) {
			StringBuffer sb = new StringBuffer();
			sb.append(text.substring(0, 25));
			sb.append("\n");
			sb.append(text.substring(26));
			notification.setLatestEventInfo(MyApplication.getInstance(), title,
					sb.toString(), pendingIntent);
		} else {
			notification.setLatestEventInfo(MyApplication.getInstance(), title,
					text, pendingIntent);
		}

		int id = new Random().nextInt();
		LogUtil.i(TAG, "id:" + id);
		manager.notify(1, notification);
	}

	protected void register(String cid) {
		UserInfo info = new UserInfo();
		MyRequest req = new MyRequest();
		req.authority = UriHelper.REALM_NAME;
		req.path = UriHelper.URL_REGISTER;
		req.paramers = generateParams(cid);
		// getDataFromTask(context, GET_USER_INFO, req, info, false, false);

		new NetWorkTask(context, false, false, null).execute(GET_USER_INFO,
				req, info);
	}

	/**
	 * 得到传递的参数
	 * 
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public Map<String, String> generateParams(String cid) {
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", "android");
		params.put("v", "1.0");
		params.put("cid", cid);
		params.put("phone_key", DeviceUtil.getMac(context));
		params.put("open_udid", DeviceUtil.getImei(context));
		params.put("phone_agent", DeviceUtil.getModel(context) + " "
				+ DeviceUtil.getOSversion(context));
		return params;
	}

}
